﻿
using Autofac;
using AutoMapper;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace SIS.Infrastructures
{
    public class Initialize
    {
        public static string ConnectionStringKey { get; set; }

        public static IContainer Container { get; private set; }

        public static void Configure(Action<ContainerBuilder> cbuilder = null)
        {
            var builder = new ContainerBuilder();

            builder.RegisterAssemblyModules(typeof(Initialize).Assembly);
            cbuilder?.Invoke(builder);

            var container = builder.Build();

            Container = container;

            Mapper.Initialize(cfg => cfg.AddProfiles(ReferencedAssemblies()));
            Mapper.Configuration.CompileMappings();
        }

        /// <summary>
        /// 获取项目程序集，排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包
        /// </summary>
        /// <returns></returns>
        public static Assembly[] ReferencedAssemblies()
        {
            Assembly[] ret = null;
            var list = new List<Assembly>();
            var deps = DependencyContext.Default;
            var libs = deps.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package");//排除所有的系统程序集、Nuget下载包
            foreach (var lib in libs)
            {
                try
                {
                    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
                    list.Add(assembly);
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (list.Any())
            {
                ret = new Assembly[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    ret[i] = list[i];
                }
            }

            return ret;
        }

    }
}
